/*
 * @Description: 
 * @Author: handongliang dongliang.han@12301.cn
 * @Date: 2023-09-22 11:21:24
 * @LastEditTime: 2024-01-02 11:20:00
 */

import './index.less'
import { useEffect, useState, useRef } from 'react'
import { Popover } from "antd";

const TextScroll: React.FC<{ value: any, width?: any, color?: any, style?: any }> = (props) => {
    const { value, width, color, style } = props
    const containerRef = useRef<any>(null);
    const textRef = useRef<any>(null);
    const [isEnter, setIsEnter] = useState<any>()
    useEffect(() => {
        const containerWidth = containerRef.current.clientWidth
        const textWidth = textRef.current.clientWidth
        if (textWidth > containerWidth && isEnter) {
            textRef.current.style.animationPlayState = 'running'; // 启动滚动动画
            textRef.current.style.animationDuration = getAnimationDuration(value)
        } else {
            textRef.current.style.animationPlayState = 'paused'; // 暂停滚动动画
            textRef.current.style.animationDuration='0s' ; 
        }
    }, [value,isEnter])

    const getAnimationDuration = (text: any) => {
        if (!text) {
            return '8s';
        }
        const textLength = text.length;
        const minDuration = 10;
        const maxDuration = 45;
        const duration = Math.min(Math.max(textLength / 5, minDuration), maxDuration);
        return `${duration}s`;
    }


    const handleMouseEnter = () => {
        setIsEnter(true)
    }

    const handleMouseLeave = () => {
        setIsEnter(false)
    }

    return (
        <Popover content={value} overlayInnerStyle={{ maxWidth: 800 }}>
            <div className='text-scroll' ref={containerRef}
                onMouseEnter={handleMouseEnter}
                onMouseLeave={handleMouseLeave}
                style={{ '--width': (typeof width) == "number" ? width + 'px' : (width || '100%'), ...style }}>
                <span className='text-scroll-container' ref={textRef} style={{ color: color }}>{value}</span>
            </div>
        </Popover>
    )
}
export default TextScroll